package com.tcwlkj.uuService.ui;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.ContactsContract;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.indexlib.IndexBar.widget.IndexBar;
import com.mcxtzhang.indexlib.suspension.SuspensionDecoration;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.model.ContactVo;
import com.tcwlkj.uuService.model.UserNameBean;
import com.tcwlkj.uuService.ui.set.TcItemDecoration;
import com.tcwlkj.uuService.utils.MyRefresh;
import com.tcwlkj.uuService.utils.ToastUtil;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/10/28 0028.
 */

public class SMSActivity extends BaseActivity {
    private SuspensionDecoration mDecoration;
    /**
     * 右侧边栏导航区域
     */
    private IndexBar mIndexBar;
    /**
     * 显示指示器DialogText
     */
    private TextView mTvSideBarHint;
    /**
     * 获取库Phone表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER = 1;
    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID = 2;
    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID = 3;
    private List<ContactVo> lists = new ArrayList<>();
    private RecyclerView mRv;
    private SwipeDelMenuAdapter mAdapter;
    private LinearLayoutManager mManager;
    private List<UserNameBean> mDatas = new ArrayList<>();
    private TwinklingRefreshLayout refresh;
    private TextView tvAllOrNo, tvSelectorNum;
    private CheckBox allCheck;
    private boolean isSelectAll = false;
    private int index = 0;
    private TextView tc_yaoqing;

    HashMap<String,String> phoneMap=new HashMap<>();
    String str="";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        changeTitle("通讯录");
        initView();
    }

    private void initView() {
        mRv = (RecyclerView) findViewById(R.id.rv);
        refresh = (TwinklingRefreshLayout) findViewById(R.id.refresh);
        tvAllOrNo = (TextView) findViewById(R.id.tvAllOrNo);
        tvSelectorNum = (TextView) findViewById(R.id.tvSelectorNum);
        allCheck = (CheckBox) findViewById(R.id.allCheck);
        tc_yaoqing = (TextView) findViewById(R.id.tc_yaoqing);
        MyRefresh.getInstance().getMyRefresh(refresh, true);
        mRv.setLayoutManager(mManager = new LinearLayoutManager(SMSActivity.this));
        mAdapter = new SwipeDelMenuAdapter(SMSActivity.this, mDatas);
        mRv.setAdapter(mAdapter);
        mRv.addItemDecoration(mDecoration = new SuspensionDecoration(SMSActivity.this, mDatas));
        mRv.addItemDecoration(new TcItemDecoration(SMSActivity.this, LinearLayoutManager.VERTICAL));

        //使用indexBar
        mTvSideBarHint = (TextView) findViewById(R.id.tvSideBarHint);//HintTextView
        mIndexBar = (IndexBar) findViewById(R.id.indexBar);//IndexBar
        allCheck.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                for (int i = 0, j = mDatas.size(); i < j; i++) {
                    mDatas.get(i).setSelected(true);
                    phoneMap.put(i+"",mDatas.get(i).getPhone()+";");
                }
                index = mDatas.size();
                tvAllOrNo.setText("取消全选");
                isSelectAll = true;
            } else {
                for (int i = 0, j = mDatas.size(); i < j; i++) {
                    mDatas.get(i).setSelected(false);
                    phoneMap.put(i+"","");
                }
                index = 0;
                tvAllOrNo.setText("全选");
                isSelectAll = false;
            }
            mAdapter.notifyDataSetChanged();
            tvSelectorNum.setText("已选中" + String.valueOf(index) + "位朋友");
        });
        //加载数据
        getData();
    }

    private void getData() {
        ContentResolver resolver = getContentResolver();
        List<ContactVo> list = new ArrayList<>();
        // 获取手机联系人
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
        // 不为空
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                ContactVo cv = new ContactVo();
                // 得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER);
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                // 得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME);
                // 得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID);
                // 得到联系人头像ID
                Long imgid = phoneCursor.getLong(PHONES_PHOTO_ID);
                // 得到联系人头像Bitamp
                Bitmap contactPhoto = null;
                // photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
                if (imgid > 0) {
                    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactid);
                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
                    contactPhoto = BitmapFactory.decodeStream(input);
                } else {
                    contactPhoto = BitmapFactory.decodeResource(getResources(), R.mipmap.personal_touxiang);
                }
                cv.setName(contactName);
                cv.setMoble(phoneNumber);
                cv.setImg(contactPhoto);
                list.add(cv);
            }
            phoneCursor.close();
            lists.clear();
            lists.addAll(list);
        }
        initDatas(lists);
    }

    //组织数据源
    private void initDatas(List<ContactVo> lists) {
        mDatas = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            UserNameBean cityBean = new UserNameBean();
            cityBean.setUserName(lists.get(i).getName());//设置名字
            cityBean.setImgKey(lists.get(i).getImg());//设置头像
            cityBean.setPhone(lists.get(i).getMoble());//设置手机号
            mDatas.add(cityBean);
        }
        mAdapter.setDatas(mDatas);
        mAdapter.notifyDataSetChanged();

        mIndexBar.setmPressedShowTextView(mTvSideBarHint)//设置HintTextView
                .setNeedRealIndex(false)//设置需要真实的索引
                .setmLayoutManager(mManager)//设置RecyclerView的LayoutManager
                .setmSourceDatas(mDatas)//设置数据
                .invalidate();
        mDecoration.setmDatas(mDatas)
                .setTitleFontSize((int) getResources().getDimension(R.dimen.ht20))
                .setColorTitleBg(getResources().getColor(R.color.backgroundcolor))
                .setColorTitleFont(getResources().getColor(R.color.divider))
                .setmTitleHeight((int) getResources().getDimension(R.dimen.ht35));
    }

    @Override
    protected void onStart() {
        super.onStart();
        tc_yaoqing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                str="";
                if(index==0){
                    ToastUtil.getInstance().show("请选择联系人");
                }else {
                    for(String key:phoneMap.keySet()){
                        str=str+phoneMap.get(key);
                    }
                    Intent intent=new Intent();
                    intent.putExtra("phone",str);
                    setResult(2,intent);
                    finish();
                }
            }
        });
    }
    private class SwipeDelMenuAdapter extends RecyclerView.Adapter<VH> {

        Context mContext;
        List<UserNameBean> mDatas;
        public SwipeDelMenuAdapter(Context mContext, List<UserNameBean> mData) {
            this.mContext = mContext;
            this.mDatas = mData;
        }

        public void setDatas(List<UserNameBean> data) {
            this.mDatas = data;
        }

        @Override
        public int getItemCount() {
            return mDatas != null && mDatas.size() > 0 ? mDatas.size() : 0;
        }

        @Override
        public VH onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ContentViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_item_newmenu, parent, false));
        }

        @Override
        public void onBindViewHolder(final VH holder, final int position) {
            holder.bindData(mDatas.get(position), position);
        }

        public class ContentViewHolder extends VH {
            LinearLayout content;
            ImageView ivAvatar;
            CheckBox cbAddFriends;
            TextView tvPhone, tvName, tvInvitation;

            public ContentViewHolder(View itemView) {
                super(itemView);
                content = $(R.id.content);
                ivAvatar = $(R.id.ivAvatar);
                cbAddFriends = $(R.id.cbAddFriends);
                tvPhone = $(R.id.tvPhone);
                tvName = $(R.id.tvName);
                tvInvitation = $(R.id.tvInvitation);
            }

            @Override
            public void bindData(final Object o, final int pos) {
                final UserNameBean mData = (UserNameBean) o;
                ivAvatar.setImageBitmap(mData.getImgKey());
                tvName.setText(mData.getUserName());
                tvPhone.setText(mData.getPhone());
                tvInvitation.setOnClickListener(view -> {
                    Intent intent=new Intent();
                    intent.putExtra("phone",tvPhone.getText().toString());
                    setResult(2,intent);
                    finish();
                });

                if (mData.isSelected()) {
                    cbAddFriends.setChecked(true);
                } else {
                    cbAddFriends.setChecked(false);
                }
                cbAddFriends.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isSelect = mData.isSelected();
                        if (!isSelect) {
                            index++;
                            phoneMap.put(pos+"",tvPhone.getText().toString()+";");
                            mData.setSelected(true);
                            if (index == mDatas.size()) {
                                isSelectAll = true;
                                tvAllOrNo.setText("取消全选");
                            }
                        } else {
                            phoneMap.put(pos+"","");
                            mData.setSelected(false);
                            index--;
                            isSelectAll = false;
                            tvAllOrNo.setText("全选");
                        }
                        tvSelectorNum.setText("已选中" + String.valueOf(index) + "位朋友");
                        notifyDataSetChanged();
                    }
                });
                content.setOnClickListener(view -> {
                    boolean isSelect = mData.isSelected();
                    if (!isSelect) {

                        index++;
                        phoneMap.put(pos+"",tvPhone.getText().toString()+";");
                        mData.setSelected(true);
                        if (index == mDatas.size()) {
                            isSelectAll = true;
                            tvAllOrNo.setText("取消全选");
                        }

                    } else {
                        phoneMap.put(pos+"","");
                        mData.setSelected(false);
                        index--;
                        isSelectAll = false;
                        tvAllOrNo.setText("全选");
                    }
                    tvSelectorNum.setText("已选中" + String.valueOf(index) + "位朋友");
                    notifyDataSetChanged();
                });

            }
        }

    }

    public class VH extends RecyclerView.ViewHolder {
        public VH(View itemView) {
            super(itemView);
        }

        public void bindData(Object o, int pos) {
        }

        protected <T extends View> T $(@IdRes int id) {
            return (T) itemView.findViewById(id);
        }
    }

}


